/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pb138.jprvyd.gui.list;

import cz.muni.fi.pb138.jprvyd.*;
import cz.muni.fi.pb138.jprvyd.gui.Main;
import cz.muni.fi.pb138.jprvyd.gui.form.PaymentMethodForm;
import cz.muni.fi.pb138.jprvyd.gui.form.InvoiceForm;
import cz.muni.fi.pb138.jprvyd.gui.model.PaymentMethod_TableModel;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.SwingWorker;

/**
 *
 * @author Jan
 */
public class PaymentMethodList extends javax.swing.JFrame {

    InvoiceForm invoiceForm;
    private List<PaymentMethod> methods;
    int rowIndex;
    SwingWorker swingWorker;
    PaymentMethodManager paymentMethodManager;
    public final boolean ADD = true;
    public final boolean REMOVE = false;
    Main mainFrame;

    /**
     * Creates new form ContactList
     */
    public PaymentMethodList() {
        this.methods = new ArrayList<PaymentMethod>();
        this.paymentMethodManager = new PaymentMethodManagerImpl();
        this.rowIndex = -1;
        initComponents();
    }

    public PaymentMethodList(InvoiceForm invoiceForm) {
        this.paymentMethodManager = new PaymentMethodManagerImpl();
        this.rowIndex = -1;
        this.invoiceForm = invoiceForm;
        List<PaymentMethod> methodsDB = paymentMethodManager.getAllPaymentMethods();
        this.methods = new ArrayList<PaymentMethod>();
        for (PaymentMethod method : methodsDB) {
            this.methods.add(method);
        }
        initComponents();
    }

    public PaymentMethodList(Main mainFrame) {
        this.paymentMethodManager = new PaymentMethodManagerImpl();
        this.rowIndex = -1;
        this.mainFrame = mainFrame;
        List<PaymentMethod> methodsDB = paymentMethodManager.getAllPaymentMethods();
        this.methods = new ArrayList<PaymentMethod>();
        for (PaymentMethod method : methodsDB) {
            this.methods.add(method);
        }
        initComponents();
        buttonDeleteMethod.setEnabled(false);
        buttonNewMethod.setEnabled(false);
    }

    private class deleteSwingWorker extends SwingWorker<Integer, Void> {

        JTable table;
        int rowIndex;

        public deleteSwingWorker(JTable table, int rowIndex) {
            this.table = table;
            this.rowIndex = rowIndex;
        }

        @Override
        protected Integer doInBackground() throws Exception {
            rowIndex = table.getSelectedRow();
            PaymentMethod_TableModel model = (PaymentMethod_TableModel) table.getModel();
            long paymentID = (Long) model.getValueAt(rowIndex, 0);
            boolean ok = true;
            InvoiceManager invoiceManager = new InvoiceManagerImpl();
            List<Invoice> invoices = invoiceManager.getAllInvoices();
            for (Invoice invoice : invoices) {
                if (invoice.getPaymentMethod().getId().equals(paymentID)) {
                    ok = false;
                }
            }
            if (ok) {
                paymentMethodManager.removePaymentMethod(paymentID);
                refreshMethods(methods.get(rowIndex), REMOVE);
            } else {
                JOptionPane.showMessageDialog(rootPane, "Payment method is tied to at least 1 invoice, can't be deleted");
            }

            return 0;
        }

        @Override
        protected void done() {
            swingWorker = null;
            buttonDeleteMethod.setEnabled(true);
        }
    }

    private class selectSwingWorker extends SwingWorker<Integer, Void> {

        Main mainFrame;
        InvoiceForm invoiceForm;
        long paymentID;

        public selectSwingWorker(InvoiceForm invoiceForm, long paymentID) {
            this.invoiceForm = invoiceForm;
            this.paymentID = paymentID;

        }

        public selectSwingWorker(Main mainFrame, long paymentID) {
            this.mainFrame = mainFrame;
            this.paymentID = paymentID;

        }

        @Override
        protected Integer doInBackground() throws Exception {
            PaymentMethodManager paymentMethodManager = new PaymentMethodManagerImpl();
            PaymentMethod method = paymentMethodManager.getPaymentMethod(paymentID);
            if (invoiceForm != null) {
                invoiceForm.paymentMethod = method;
                invoiceForm.textFieldPayment.setText(method.getName());
            } else if (mainFrame != null) {
                mainFrame.setPaymentMethod(method);
            }
            return 0;
        }

        @Override
        protected void done() {
            swingWorker = null;
            buttonSelect.setEnabled(true);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tablePayment = new javax.swing.JTable();
        buttonNewMethod = new javax.swing.JButton();
        buttonDeleteMethod = new javax.swing.JButton();
        buttonSelect = new javax.swing.JButton();
        buttonCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("JPrVyd - Managing payment methods");

        tablePayment.setModel(new PaymentMethod_TableModel(methods));
        tablePayment.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablePaymentMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tablePayment);

        buttonNewMethod.setText("New payment method");
        buttonNewMethod.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonNewMethodActionPerformed(evt);
            }
        });

        buttonDeleteMethod.setText("Delete method");
        buttonDeleteMethod.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonDeleteMethodActionPerformed(evt);
            }
        });

        buttonSelect.setText("Select");
        buttonSelect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSelectActionPerformed(evt);
            }
        });

        buttonCancel.setText("Cancel");
        buttonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(buttonNewMethod, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGap(125, 125, 125)
                                .addComponent(buttonDeleteMethod))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(buttonSelect)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(buttonCancel))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 265, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonDeleteMethod)
                    .addComponent(buttonNewMethod))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonSelect)
                    .addComponent(buttonCancel))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCancelActionPerformed
        this.dispose();
    }//GEN-LAST:event_buttonCancelActionPerformed

    private void buttonSelectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSelectActionPerformed
        rowIndex = tablePayment.getSelectedRow();
        if (rowIndex == -1) {
            JOptionPane.showMessageDialog(rootPane, "No method selected");
        } else {
            if (swingWorker != null) {
                throw new IllegalStateException("Operation in progress");
            }
            buttonSelect.setEnabled(false);
            PaymentMethod_TableModel model = (PaymentMethod_TableModel) tablePayment.getModel();
            Long paymentID = (Long) model.getValueAt(rowIndex, 0);
            if (invoiceForm != null) {
                swingWorker = new selectSwingWorker(this.invoiceForm, paymentID);
                swingWorker.execute();
            } else if (mainFrame != null) {
                swingWorker = new selectSwingWorker(this.mainFrame, paymentID);
                swingWorker.execute();
            }
            this.dispose();
        }
    }//GEN-LAST:event_buttonSelectActionPerformed

    private void buttonNewMethodActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonNewMethodActionPerformed
        PaymentMethodForm form = new PaymentMethodForm(this);
        form.setVisible(true);
    }//GEN-LAST:event_buttonNewMethodActionPerformed

    private void buttonDeleteMethodActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonDeleteMethodActionPerformed
        rowIndex = tablePayment.getSelectedRow();
        if (rowIndex == -1) {
            JOptionPane.showMessageDialog(rootPane, "No method selected");
        } else {
            int choice = JOptionPane.showConfirmDialog(rootPane, "Delete method?", null, JOptionPane.YES_NO_OPTION);
            if (choice == 0) {
                if (swingWorker != null) {
                    throw new IllegalStateException("Operation in progress");
                }
                buttonDeleteMethod.setEnabled(false);
                swingWorker = new deleteSwingWorker(tablePayment, rowIndex);
                swingWorker.execute();
            }
        }
    }//GEN-LAST:event_buttonDeleteMethodActionPerformed

    private void tablePaymentMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablePaymentMouseClicked
        if (rowIndex == tablePayment.getSelectedRow()) {
            this.buttonSelectActionPerformed(null);
        } else {
            rowIndex = tablePayment.getSelectedRow();
        }
    }//GEN-LAST:event_tablePaymentMouseClicked

    public void refreshMethods(PaymentMethod method, boolean action) {

        if (action == ADD) {
            methods.add(method);
        } else if (action == REMOVE) {
            methods.remove(method);
        }
        rowIndex = -1;
        tablePayment.updateUI();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PaymentMethodList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PaymentMethodList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PaymentMethodList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PaymentMethodList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new PaymentMethodList().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonCancel;
    private javax.swing.JButton buttonDeleteMethod;
    private javax.swing.JButton buttonNewMethod;
    private javax.swing.JButton buttonSelect;
    private javax.swing.JScrollPane jScrollPane1;
    public javax.swing.JTable tablePayment;
    // End of variables declaration//GEN-END:variables
}
